import { useState, createContext, useRef, useContext } from "react";
import MessageBoxBase from "./MessageBox";

const MessageBoxContext = createContext({});

function MessageBoxProvider(props) {
    let [showModal, setShowModal] = useState(false);

    let [title, setTitle] = useState('');
    let [message, setMessage] = useState('');
    let [type, setType] = useState(null);
    let resolveRef = useRef(null); // 因为与 UI 无关，用 ref 不用 state

    const handleResult = (result) => {
        resolveRef.current(result);
        setShowModal(false);
    };

    const show = (title, message, type) => {
        setTitle(title);
        setMessage(message);
        setType(type);
        setShowModal(true);

        return new Promise((resolve, reject) => {
            resolveRef.current = resolve;
        });
    };

    return (
        <MessageBoxContext.Provider value={show}>
            <MessageBoxBase
                title={title}
                message={message}
                type={type}
                showModal={showModal}
                onResult={handleResult}
            />
            {props.children}
        </MessageBoxContext.Provider>
    );
}

/** 
 * 以 Context 方式使用 MessageBox。
 * @return {(title: string, message: string, type: string) => Promise<string>}
 */
function useMessageBox() {
    return useContext(MessageBoxContext);
}


export default useMessageBox;
export { MessageBoxProvider, MessageBoxContext };